/**
 * @author manel
 */

$(document).ready(function() {
 	
	start();
});

MM = {
	scale: 5,
	boundingBox: false
}

function start() {
 	
	// init canvas
    var screen = $("#screen");
    var ctx = (screen[0]).getContext("2d");

	// db
	frameDb = new dotDb;
	frameDb.createTable("layer1");
	frameDb.createTable("boundingBox");
	
	function drawNote(val, pos) {
		if (typeof val != "string" || val.length == 0) return;
		
		wrap(function() {
			ctx.fillStyle = "black";
			ctx.fillRect(pos[0],pos[1],2,2);
		});
		
		wrap(function() { // draw box
			ctx.strokeStyle = "black";
			ctx.fillStyle = "white";
			ctx.strokeRect(pos[0]-(val.length*MM.scale), pos[1]-15,val.length*MM.scale*2,30);
		});
		
		
		wrap(function() {
		ctx.fillStyle = "red";
			ctx.mozTextStyle ="12pt Arial";
			ctx.translate(pos[0] - (val.length*(MM.scale/1.5)),pos[1]+5);
			ctx.mozDrawText(val);
		});	
	}


	function wrap(fn) {
		ctx.save();
		fn();
		ctx.restore();
	}
	
	
	function checkBB(table, pos) {
		var isInside = frameDb.filter(table, function(e) {
			if (pos[0]>e.x && pos[0]<(e.x+e.dx) && pos[1]>e.y && pos[1]<(e.y+e.dy)) {
				screen.css("cursor","pointer");
				return false;				
			}
			return true;
		});
		console.log(isInside);
		if (isInside) {
			screen.css("cursor","default");
		}
	}
	
	// event handlers
	
	screen.click(function(e) {
		var pos = [e.clientX-screen[0].offsetLeft, e.clientY-screen[0].offsetTop];

		value = prompt("Title","");
		
		if (typeof value == "undefined" || value.length<1) return;
		
		drawNote(value, pos);
		
		frameDb.insert("layer1", {"value":value, "position":pos});
		frameDb.insert("boundingBox", {
			"x": pos[0] - (value.length * MM.scale),
			"y": pos[1] - 15,
			"dx": value.length * MM.scale * 2,
			"dy": 30
		});				
	});
	
	screen.mousemove(function(e) {
		var pos = [e.clientX-screen[0].offsetLeft, e.clientY-screen[0].offsetTop];

		checkBB("boundingBox", pos); 

	});
	
}
